package p.ithorns.integration.sharding;

import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;

import java.time.LocalDateTime;
import java.util.Collection;

/**
 * PreciseDatabaseSharding
 * 库精确分片算法
 *
 * @author ithorns
 * @version 1.0
 * @date 2021/9/6 23:03
 */
public class PreciseDatabaseSharding implements PreciseShardingAlgorithm<Long> {

    /**
     * 精确分片算法
     *
     * @param availableTargetNames 所有配置的库列表
     * @param shardingValue        分片值，也就是save_time_com的值
     * @return                     所匹配库的结果
     */
    @Override
    public String doSharding(Collection<String> availableTargetNames, PreciseShardingValue<Long> shardingValue) {

        Long value = shardingValue.getValue();

        // 库后缀
        LocalDateTime dateTime = LocalDateUtil.asLocalDateTime(value);
        String yearStr = String.valueOf(dateTime.getYear());

        if (value <= 0) {
            throw new UnsupportedOperationException("preciseShardingValue is null");
        }

        for (String availableTargetName : availableTargetNames) {
            if (availableTargetName.endsWith(yearStr)) {
                return availableTargetName;
            }
        }
        throw new UnsupportedOperationException();
    }

}
